import { useEffect, useState } from 'react'
import style from './index.module.scss'
import logo from '@/assets/img/heima.png'
import { GetMenuFnc } from '@/api/menu'
import { useDispatch } from 'react-redux'
import { saveToken } from '@/reduxToolkit/reducers/token'
import { savePath, saveKeys } from '@/reduxToolkit/reducers/path'
import { removeCookie } from '@/utils/cookie'
import { UsergroupDeleteOutlined, GroupOutlined, LockOutlined, MacCommandOutlined, InsertRowBelowOutlined } from '@ant-design/icons';

import { Button, Menu, ConfigProvider, message, App } from 'antd'
import { NavLink, Outlet, useNavigate } from 'react-router-dom';
import { useSelector } from 'react-redux'


const MenuPage = () => {
  const dispath = useDispatch()
  const navigate = useNavigate()
  const [nav, setNav] = useState([]) // menu 菜单数据
  const [subKey] = useState(['sub1', 'sub2', 'sub3', 'sub4', 'sub5'])
  const [openKeys, setOpenKeys] = useState([useSelector((state: {path: {openKey: string}}) => state.path.openKey)]) // 当前展开的 SubMenu 菜单项 key 数组
  const [icon] = useState([<UsergroupDeleteOutlined/>, <GroupOutlined/>, <LockOutlined/>, <MacCommandOutlined/>, <InsertRowBelowOutlined/> , <LockOutlined/>])
  const selectedKeys = useSelector((state: {path: any}) => state.path.value)

  // 数据初始化
  const init = async () => {
    const res = await GetMenuFnc()
    if(res.data.meta.status === 200) {
      let arr: any = []
      res.data.data.forEach((item: {authName: string, children: []}, index: number) => {
        arr.push({
          label: item.authName,
          key: subKey[index],
          icon: icon[index],
          children: (item.children && item.children.length !== 0) ? 
          item.children.map((itemChild: {path: string, authName: string, id: number}) => {
            return {
              label: <NavLink to={itemChild.path} onClick={() => menuClick(itemChild.path, index)}>{itemChild.authName}</NavLink>,
              key: itemChild.id
            }
          }) : ''
        })
      })
      setNav(arr)
    }
  }
  useEffect(() => {init()}, [])

  // menu菜单切换  手风琴效果
  const selectItem = (openKeys: string[]) => {
   const keys = openKeys[1]
   setOpenKeys([keys])
  }

  // 退出
  const logout = () => {
    message.success('退出成功', 1.5, () => {
      dispath(saveToken(null))
      dispath(savePath(''))
      dispath(saveKeys(''))
      removeCookie('token')
      removeCookie('path')
      removeCookie('keys')
      navigate('/login')
    })
  }

  // 点击menu-item 保存菜单当前激活项 放在pinia里面 让数据持久化 刷新也不会丢失
  const menuClick = (path: string, index: number) => {
    dispath(savePath(path))
    dispath(saveKeys(subKey[index]))
  }

  return (
   <ConfigProvider>
    <App>
      {/* header部分  */}
      <div className={style.header}>
        <div className={style.headerLeft}>
          <img src={logo} alt=""/>
          <span>电商后台管理系统</span>
        </div>
        <div className={style.headerRight}>
          <Button onClick={logout}>退出</Button>
        </div>
      </div>

      <div className={style.content}>
      {/* 左侧menu导航部分 */}
      <div className={style.contentLeft} style={{width: '200px'}}>
          <Menu mode='inline' items={nav} openKeys={openKeys} selectedKeys={selectedKeys} onOpenChange={selectItem}/>
      </div>

      {/* 右侧子组件内容 */}
      <div className={style.contentRight}>
        <Outlet/>
      </div>
      </div>
     </App>
   </ConfigProvider>
  )
}

export default MenuPage

